import React, { useEffect, useState, useRef, useImperativeHandle, forwardRef } from 'react';
import { Form, Input, Space, Typography } from 'antd';
import { selectUserInfo } from '@/store/slice/auth';
import WarehouseSelector from './warehouse-selector';
import ColumnList from './column-list';
import { saveTable } from '@/service/api/meta';
import type { ColumnListRef } from './column-list';
const { Text } = Typography;

interface DatasetCreatorProps {
  table: Bn.Meta.MetaTable | undefined;
  close: () => void;
}

export interface DatasetCreatorRef {
  save: () => Promise<number|null>;
}

const DatasetCreator = forwardRef(({ table, close }: DatasetCreatorProps, ref: React.Ref<DatasetCreatorRef>) => {
  const columnListRef = useRef<ColumnListRef>(null);
  const currentUser = useAppSelector(selectUserInfo);
  const [warehouse, setWarehouse] = useState<Bn.Meta.MetaWarehouse>();
  const [form] = Form.useForm<Bn.Meta.MetaTable>();
  const _tableName = Form.useWatch('tableName', form);

  const save = async (): Promise<number|null> => {
    const columns = columnListRef.current?.getColumns();
    if (!columns || columns.length == 0) {
      window.$message?.error({ content: '未选择数据表字段' });
      return null;
    }
    if (table) {
      table.columns = columns;
      table.dbId = warehouse?.id!;
      table.ownerId = currentUser.id;
      table.tableType = 'DUPLICATE';
      const new_table_id = (await saveTable(table)).data;
      if (new_table_id) {
        window.$message?.success(`数据表${table.tableName}创建成功`);
        if (close) { close(); }
      }
    }
    return null;
  }

  const onWarehouseChanged = (warehouse: Bn.Meta.MetaWarehouse) => {
    setWarehouse(warehouse);
  }

  useImperativeHandle(ref, () => ({ save }));

  useEffect(() => {
    form.setFieldValue('tableName', table?.tableName);
  }, [table]);

  return (
    <Space
      direction="vertical"
      size="middle"
      style={{ display: 'flex' }}
    >
      <Text strong>基础信息</Text>
      <Form
        form={form}
        name="DatasetCreator"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
        size="large"
        initialValues={{
          tableName: table?.tableName
        }}
      >
        <Form.Item<Bn.Meta.MetaTable>
          label="数据仓库"
          name="dbId"
        >
          <WarehouseSelector onWarehouseChanged={onWarehouseChanged}></WarehouseSelector>
        </Form.Item>
        <Form.Item<Bn.Meta.MetaTable>
          label="数据集名称"
          name="tableName"
          rules={[
            { required: true, message: '请输入数据集名称' }
          ]}
          extra={`创建名称: ods_bm_${_tableName?.toLowerCase()}_i_1d`}
        >
          <Input showCount maxLength={64} placeholder="请输入新建数据集名称" />
        </Form.Item>
      </Form>

      <Text strong>字段列表</Text>
      <ColumnList
        ref={columnListRef}
        table={table}
      ></ColumnList>
    </Space>
  );
});

export default DatasetCreator;
